package atguigu.com.edu.app.dim;

import atguigu.com.edu.func.DimSinkFunction;
import atguigu.com.edu.bean.TableProcess;
import atguigu.com.edu.func.TableProcessFunction;
import atguigu.com.edu.util.MyKafkaUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;

import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;



public class DimApp {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备

        //1.1 指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);
     /*   //TODO 2.检查点相关设置
        //2.1 开启检查点
        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);

        //2.2 设置检查点超时时间
         env.getCheckpointConfig().setCheckpointTimeout(60000L);
        //2.3 设置job取消之后，检查点是否保留
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.
                ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION); retain-on-cancellation
        //2.4 设置两个检查点之间最小时间间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000L);
        //2.5 设置重启策略
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30),Time.seconds(3)));
        //2.6 设置状态后端
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME","atguigu");*/

        //2.1开启检查点
        //2.2设置超时时间
        //2.3设置重启促使
        //2.4设置两个最小时间
        //2.5设置两个job取消是否保留
        //2.6状态后端


        //TODO 3.从kafka的topic_db主题中读取数据
        String topic = "topic_db";
        String groupId = "dim_app_group";

        FlinkKafkaConsumer<String> kafkaConsumer = MyKafkaUtil.getKafkaConsumer(topic, groupId);
        DataStreamSource<String> stringDataStreamSource = env.addSource(kafkaConsumer);



        //TODO 4.对读取的数据进行类型转换           jsonStr->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = stringDataStreamSource.map(new MapFunction<String, JSONObject>() {
            @Override
            public JSONObject map(String s) throws Exception {
                return JSON.parseObject(s);
            }
        });
        //stringDataStreamSource.map(JSON::parseObject);
        //TODO 5.简单的ETL 脏数据直接过滤掉
        SingleOutputStreamOperator<JSONObject> filter = jsonObjDS.filter(new FilterFunction<JSONObject>() {
            @Override
            public boolean filter(JSONObject jsonObject) throws Exception {
                try {
                    jsonObject.getJSONObject("data");
                    if (jsonObject.getString("type").equals("bootstrap-start") || jsonObject
                            .getString("type").equals("bootstrap-complete")) {
                        return false;
                    }
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }
        });
        // filter.print(">>>");

        //TODO 6.使用FlinkCDC读取配置表数据
        MySqlSource<String> mySqlSource = MySqlSource.<String>builder()
                .hostname("hadoop201")
                .port(3306)
                .databaseList("edu0411_config")
                .tableList("edu0411_config.table_process")
                .username("root")
                .password("000000")
                .startupOptions(StartupOptions.initial())
                .deserializer(new JsonDebeziumDeserializationSchema())
                .build();

        DataStreamSource<String> mySqlDS = env
                .fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "MySQL Source");
        // mySqlDS.print("....");
        //TODO 7.对配置流进行广播  得到广播流
        MapStateDescriptor<String, TableProcess> mapStateDescriptor
                = new MapStateDescriptor<String, TableProcess>("mapStateDescriptor",String.class,TableProcess.class);


        BroadcastStream<String> broadcastDS = mySqlDS.broadcast(mapStateDescriptor);

        //TODO 8.将主流业务数据和广播流配置数据进行关联  connect
        BroadcastConnectedStream<JSONObject, String> connectDS = filter.connect(broadcastDS);

        //TODO 9.分别对两条流数据进行处理
        SingleOutputStreamOperator<JSONObject> dimDS = connectDS.process(
                new TableProcessFunction(mapStateDescriptor)
        );

        //TODO 10.将维度数据写到phoenix中
        dimDS.print(">>>>");
        dimDS.addSink(new DimSinkFunction());
        env.execute();
    }
}
